package cn.crex1.netty.server;

import cn.crex1.netty.handler.HttpHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * @author zzh
 */
public class HttpServer {

    private final Integer port;

    public HttpServer(Integer port) {
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new HttpServer(8888).start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void start() throws InterruptedException {
        ServerBootstrap bootstrap=new ServerBootstrap();
        NioEventLoopGroup group=new NioEventLoopGroup();
        bootstrap.group(group).
                channel(NioServerSocketChannel.class).
                childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("initChannel ch:" + ch);
                        ch.pipeline().
                                addLast("decoder",new HttpRequestDecoder()).
                                addLast("encoder",new HttpResponseEncoder()).
                                addLast("aggregator",new HttpObjectAggregator(512*1024)).
                                addLast("handler",new HttpHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG,128)
                .option(ChannelOption.SO_KEEPALIVE,Boolean.TRUE);
        bootstrap.bind(port).sync();
    }
}
